<?php

namespace App\Policies;

use App\Models\AccessLog;
use Illuminate\Support\Facades\Request;

class Observer {

	// creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored

	public function saved($model) {
		return $this->addLog($model);
	}

	public function updated($model) {
		return $this->addLog($model);
	}

	public function deleted($model) {
		return $this->addLog($model);
	}

	public function addLog($model) {
		$token = session('token');
		$user_id = empty($token) ? 0 : $token['user_id'];

		$method = Request::method();
		if ($method == 'GET') {
			return true;
		}

		$log = new AccessLog;
		$log->user_id = $user_id;

		$log->action = safe(Request::path());
		$log->method = safe(Request::method(), 10);
		$log->content = safe(json_encode(Request::all()), 200);

		$log->table_name = safe($model->getTable(), 50);
		$log->record_id = isset($model->id) ? $model->id : 0;

		$log->time = to_date(time());
		$log->ip = Request::ip();
		return $log->save();
	}

}